<?php
defined('EXEC') or die();
$transacao = 'manter_profissional';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}

//Importando a classes
Loader::import('com.atitudeweb.SQL');

//Exclusão de vários ou um registro
if(isset($_POST['checkdel'])){
	if($auth->isDelete($transacao)){
		if(SQL::remove('tethys.tb_profissional', 'ci_profisional', $_POST['checkdel'])){
			Util::notice('Profissional', 'Excluída com sucesso!');
		}
		else{
			Util::notice('Profissional', 'Houve um erro ao excluir!', 'error');
		}
	}
	else{
		Util::info(Config::AUTH_MESSAGE);
	}
}

//Alteração ou inclusão de um registro
if(isset($_GET['db']) && isset($_GET['form'])){
	$ci_profissional = $_GET['form'];
	$nm_profissional = addslashes(strtoupper($_POST['nm_profissional']));
	$fl_ativo = $_POST['fl_ativo'];
	$nr_telefone = $_POST['nr_telefone'];
	$nr_celular = $_POST['nr_celular'];
	$ds_email = $_POST['ds_email'];
	$ds_color = $_POST['ds_color'];

	if($_GET['form'] == 0){ //cadastro
		$sqlRow = "SELECT nextval('tethys.tb_profissional_ci_profissional_seq') as ci_profissional";
		$ciRow = Connection::query($sqlRow)->fetch();
		$ci_profissional = $ciRow['ci_profissional'];
		$sql = "INSERT INTO tethys.tb_profissionais(
        	ci_profissional, nm_profissional, fl_ativo, nr_telefone, nr_celular,
            ds_email, ds_color) VALUES ($ci_profissional, '$nm_profissional', '$fl_ativo', '$nr_telefone',
			'$nr_celular', '$ds_email', '{$ds_color}');";

	}elseif($_GET['form'] > 0){ //alteração
		$sql = "UPDATE tethys.tb_profissionais
				   SET nm_profissional='$nm_profissional',
				   fl_ativo='$fl_ativo', nr_telefone='$nr_telefone', nr_celular='$nr_celular',
				   ds_email='$ds_email',ds_color='{$ds_color}'
				 WHERE ci_profissional = ".$_GET['form'];
	}

	if(execute($sql)){
		Controller::setInfo('Cliente', 'Salvo com sucesso!');
		Controller::redirect(Util::setLink(array('form=null', 'db=null')));
	}
	else{
		Util::notice('Cliente', 'Ocorreu um erro!', 'error');
	}
}

if(isset($_GET['form'])){ //Formulário para adição ou alteração de registro
	if($_GET['form'] == 0){
		if(!$auth->isCreate($transacao)){
			Util::info(Config::AUTH_MESSAGE);
			return true;
		}
	}
	else{
		if(!$auth->isUpdate($transacao)){
			Util::info(Config::AUTH_MESSAGE);
			return true;
		}
		$rowEdit = query("select * from tethys.tb_profissionais where ci_profissional = ".$_GET['form'])->fetch();
	}
}
else{ //Consulta no banco para listagem dos registros
$where = '';
	if(@$_POST['search1']){
		$term = addslashes($_POST['search1']);
		$where =  "nm_profissional ilike '%{$term}%'";
	}
	$sql = "select * from tethys.tb_profissionais
	where 1=1 $where
	order by nm_profissional
	limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$query = query($sql);
	$sqlNum = "select count(*) as num from tethys.tb_profissionais
	where 1=1 $where";
	$rowNum = query($sqlNum)->fetch();
	$registros = $rowNum['num'];
	$paginacao = Util::pagination($registros, 4);
}

//Deixando pré-selecinada a opção masculino
if(@!@$rowEdit['fl_ativo'])
	@$rowEdit['fl_ativo'] = '1';
?>
<div id="container">
    <table class="actiontable">
		<tr>
			<td width="40">
				<img src="assets/grupo.png"/>
			</td>
			<td>
				<span class="actiontitle">Protéticos</span>
				<span class="actionview"> - <?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
				</span>
			</td>
			<?php if(!isset($_GET['form'])){ ?>
				<td align="right">
					<button id="btAdd" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-plus-sign"></span> Novo</button>
				</td>
			<?php } else{ ?>
				<td align="right">
					<button id="btVoltar" class="btn btn-success btn-sm" onclick="window.location='?page=cadastros/profissionais';"><span class="glyphicon glyphicon-chevron-left"></span> Voltar</button>
				</td>
			<?php } ?>
		</tr>
	</table>
	<?php if(!isset($_GET['form'])){ ?>
	<form action="<?php echo Util::setLink(array('p=null')); ?>" method="post">
		<table border="0" cellpadding="2" cellspacing="2" align="center">
			<tr>
				<td align="right">Profissional:</td>
				<td>
					<table border="0" cellpadding="0" cellspacing="0" width="580">
						<tr>
							<td width="200">
								<input type="text" name="search1" id="search1" value="<?php echo @$_POST['search1']; ?>" class="form-control input-sm" style="width:290px;" />
							</td>
							<td width="100" align="right">
								<button id="btSearch" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-search"></span> Consultar</button>
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</form>
	<?php } ?>
	<?php if(!isset($_GET['form'])){ ?>
	<form action="<?php echo Util::setLink(array('del='.$query->rowCount())) ?>" method="post" id="formSearch">
		<table class="tablelist ui-widget ui-widget-content">
			<thead>
				<tr class="ui-widget-header">
					<th width="25" class="check"><input type="checkbox" id="btCheckAll" /></th>
					<th>ID</th>
					<th>Profissional</th>
					<th>Telefone</th>
					<th>Celular</th>
					<th>Email</th>
					<th></th>
					<th></th>
				</tr>
			</thead>
			<tbody>
			<?php
			$count = 0;
			while($row = $query->fetch()){
				echo '<tr>
		            	<td class="check"><input type="checkbox" class="btCheck" name="checkdel[]" value="'.$row['ci_profissional'].'"/></td>
		                <td>'.$row['ci_profissional'].'</td>
		                <td>'.strtoupper($row['nm_profissional']).'</td>
		                <td>'.$row['nr_telefone'].'</td>
		                <td>'.$row['nr_celular'].'</td>
		                <td>'.$row['ds_email'].'</td>
		                <td>'.(($row['fl_ativo'] == '1') ? '<img src="assets/ok.png" title="Profissional Ativo"/>' : '<img src="assets/cancel.png" title="Profissional Desativado"/>').'</td>
		                <td width="30" align="center">
		                	<div onclick="window.location=\''.Util::setLink(array('form='.$row['ci_profissional'])).'\';" class="btEdit ui-widget ui-helper-clearfix" title="Editar">
						    	<div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"></span></div>
						    </div>
		                </td>
		        	</tr>';
				$count++;
			}
			?>
			</tbody>
		</table>
	</form>
	<button id="btDel" title="Excluir selecionados" class="btn btn-success btn-sm" style="float:left;"><span class="glyphicon glyphicon-trash"></span>Excluir</button>
	<?php echo $paginacao; ?>
	<?php } else{ ?>
	<div class="validateTips ui-corner-all"	style="width: 720px; margin: 0 auto; text-align: center;">Preencha corretamente o formulário.</div>
	<form action="<?php echo Util::setLink(array('db=1')) ?>" method="post"	id="formInsertEdit" onsubmit="return test();">
		<table border="0" align="center">
			<tr>
				<td align="right">Profissional *:</td>
				<td><input type="text" id="nm_profissional" name="nm_profissional"
					value="<?php echo trim(strtoupper(@$rowEdit['nm_profissional'])); ?>"
					class="form-control input-sm" size="30" /></td>
			</tr>
			<tr>
				<td align="right">Telefone:</td>
				<td><input type="text" id="nr_telefone" name="nr_telefone"  onkeypress="mask(this, telefone)"
					value="<?php echo trim(strtoupper(@$rowEdit['nr_telefone'])); ?>"
					class="form-control input-sm" size="30" /></td>
			</tr>
			<tr>
				<td align="right">Celular:</td>
				<td><input type="text" id="nr_celular" name="nr_celular" onkeypress="mask(this, telefone)"
					value="<?php echo trim(strtoupper(@$rowEdit['nr_celular'])); ?>"
					class="form-control input-sm" size="30" /></td>
			</tr>
			<tr>
				<td align="right">Email:</td>
				<td><input type="text" id="ds_email" name="ds_email"
					value="<?php echo @$rowEdit['ds_email']; ?>"
					class="form-control input-sm" size="30" /></td>
			</tr>
			<tr>
				<td align="right">Cor:</td>
				<td><input type="text" id="ds_color" name="ds_color"
					value="<?php echo @$rowEdit['ds_color']; ?>"
					class="color {required:false}" size="30" /></td>
			</tr>
			<tr>
				<td align="right">Situação:</td>
				<td>
				<label><input type="radio" id="fl_ativo_s" name="fl_ativo"
					value="1" class="text ui-widget-content ui-corner-all" size="30"
					<?php echo ((@$rowEdit['fl_ativo'] == '1') ? 'checked' : null);?>/>
					Ativo
				</label>
				<label>
					<input type="radio" id="fl_ativo_n" name="fl_ativo"
					value="2" class="text ui-widget-content ui-corner-all" size="30"
					<?php echo ((@$rowEdit['fl_ativo'] == '2') ? 'checked' : null);?>/>
					Desativo
				</label>
				</td>
			</tr>
		</table>
		<table border="0" align="center" height="45">
			<tr><td width="40"><img id="loader" src="assets/loading.gif" style="display:none;"/></td>
			<td><button id="btInsertEdit" class="btn btn-success btn-sm" type="submit"><span class="glyphicon glyphicon-floppy-disk"></span> Salvar</button></td>
			<td width="40">&nbsp;</td></tr>
		</table>
	</form>
	<?php } ?>
</div>
<div id="dialog_del" title="Aviso">
<p>Tem certeza que deseja excluir os registros selecionados?</p>
</div>
<script type="text/javascript">
	$(function(){

	});

	function test(){
		var valid = true;
		var nm_profissional = $("#nm_profissional").val();
		if (nm_profissional == '') {
			updateTips('O Campo profissional está vázio');
			valid = false;
		}else{
			$("#formInsertEdit").find("input").each(function(index){
				$(this).removeClass("ui-state-error");
			});
			valid = valid && checkLength('nm_profissional', 'Profissional', 2);
		}
		return valid;
	}
</script>
